//
//  NoteReviewControllerExtensions.swift
//  hello
//
//  Created by 赵康 on 2025/4/1.
//

import Vapor
import Fluent

extension NoteReviewController {
    // 同步复习数据
  @Sendable
  func syncReviewData(req: Request) async throws -> BasicResponse {
    let userID = try req.authenticatedUserID
    let syncRequest = try req.content.decode(SyncReviewData.self)
    
    switch syncRequest.direction {
      case .localToServer:
          // 本地数据覆盖服务器
        for reviewData in syncRequest.reviewData {
            // 查找或创建复习记录
          let review = try await NoteReview.query(on: req.db)
            .filter(\.$note.$id == reviewData.noteID)
            .filter(\.$user.$id == userID)
            .first()
          ?? NoteReview(noteID: reviewData.noteID, userID: userID)
          
            // 更新基本数据
          review.difficulty = reviewData.difficulty
          review.nextReviewDate = reviewData.nextReviewDate
          review.reviewCount = reviewData.reviewCount
          review.lastReviewDate = reviewData.lastReviewDate
          
            // 更新Anki算法数据
          if let easeFactor = reviewData.easeFactor {
            review.easeFactor = easeFactor
          }
          if let interval = reviewData.interval {
            review.interval = interval
          }
          if let learningStage = reviewData.learningStage {
            review.learningStage = learningStage
          }
          if let lapseCount = reviewData.lapseCount {
            review.lapseCount = lapseCount
          }
          
          review.updatedAt = Date()
          
            // 保存
          try await review.save(on: req.db)
          
            // 更新笔记状态
          if let note = try await Note.find(reviewData.noteID, on: req.db) {
            note.reviewStatus = reviewData.difficulty == .ignored ? .completed : .scheduled
            try await note.save(on: req.db)
          }
        }
        
      case .serverToLocal:
          // 不需要在服务器端做任何处理，只返回当前服务器数据
          // 前端会处理服务器数据覆盖本地的逻辑
        break
        
      case .merge:
          // 合并策略：以最近更新的数据为准
        for reviewData in syncRequest.reviewData {
          if let existingReview = try await NoteReview.query(on: req.db)
            .filter(\.$note.$id == reviewData.noteID)
            .filter(\.$user.$id == userID)
            .first() {
            
              // 只有当本地数据更新时才使用本地数据
            if let localUpdated = reviewData.lastReviewDate,
               let serverUpdated = existingReview.lastReviewDate,
               localUpdated > serverUpdated {
              
                // 更新基本数据
              existingReview.difficulty = reviewData.difficulty
              existingReview.nextReviewDate = reviewData.nextReviewDate
              existingReview.reviewCount = reviewData.reviewCount
              existingReview.lastReviewDate = reviewData.lastReviewDate
              
                // 更新Anki算法数据
              if let easeFactor = reviewData.easeFactor {
                existingReview.easeFactor = easeFactor
              }
              if let interval = reviewData.interval {
                existingReview.interval = interval
              }
              if let learningStage = reviewData.learningStage {
                existingReview.learningStage = learningStage
              }
              if let lapseCount = reviewData.lapseCount {
                existingReview.lapseCount = lapseCount
              }
              
              existingReview.updatedAt = Date()
              
              try await existingReview.save(on: req.db)
              
                // 更新笔记状态
              if let note = try await Note.find(reviewData.noteID, on: req.db) {
                note.reviewStatus = reviewData.difficulty == .ignored ? .completed : .scheduled
                try await note.save(on: req.db)
              }
            }
          } else {
              // 如果服务器没有此记录，创建新记录
            let review = NoteReview(
              noteID: reviewData.noteID,
              userID: userID,
              difficulty: reviewData.difficulty,
              nextReviewDate: reviewData.nextReviewDate,
              reviewCount: reviewData.reviewCount,
              lastReviewDate: reviewData.lastReviewDate,
              easeFactor: reviewData.easeFactor ?? 2.5,
              interval: reviewData.interval ?? 0,
              learningStage: reviewData.learningStage ?? .new,
              lapseCount: reviewData.lapseCount ?? 0
            )
            try await review.save(on: req.db)
            
              // 更新笔记状态
            if let note = try await Note.find(reviewData.noteID, on: req.db) {
              note.reviewStatus = reviewData.difficulty == .ignored ? .completed : .scheduled
              try await note.save(on: req.db)
            }
          }
        }
    }
    
      // 更新最后同步时间
    if let settings = try await UserReviewSettings.query(on: req.db)
      .filter(\.$user.$id == userID)
      .first() {
      settings.lastSyncDate = Date()
      try await settings.save(on: req.db)
      
        // 清除设置缓存
      let settingsCacheKey = CacheConfig.KeyBuilder.userReviewSettings(userID: userID)
      try await req.cache.delete(forKey: settingsCacheKey, on: req.redis)
    }
    
      // 清除今日复习列表缓存
    let todayReviewsCacheKey = CacheConfig.KeyBuilder.todayReviews(userID: userID)
    try await req.cache.delete(forKey: todayReviewsCacheKey, on: req.redis)
    
    return BasicResponse(success: true, message: "同步成功")
  }
}
